<?

require_once "../init.php";

//Qi_Http::modo_texto();

Qi_Db::conectar();
Qi_Db::query("CREATE DATABASE IF NOT EXISTS qi");
Qi_Db::selecionar_banco("qi");

require_once "fixtures.php";

$sql = <<<EOF
SELECT * FROM categorias
	LEFT JOIN sub_categorias ON (categoria_id = categorias.id)
	LEFT JOIN produtos ON (sub_id = sub_categorias.id)
	ORDER BY categorias.id, sub_categorias.id, produtos.id
EOF;

$result = Qi_Db::query($sql);

echo $result->toHtmlTable();

class Qi_It_Group extends NoRewindIterator
{
	private $field;
	private $last = null;
	private $it;
	private $parent;
	private $pause = false;

	public function __construct($it, $field, $parent = null)
	{
		if ($parent === null) $it->rewind();
		parent::__construct($it);
		$this->field = $field;
		$this->it = $it;
		$this->parent = $parent;
		$this->update_last();
	}

	public function next()
	{
		if ($this->pause):
			$this->pause = false;
			$this->update_last();
			return;
		endif;
		do {
			parent::next();
		}while($this->valid() && $this->same());
		$this->update_last();
	}

	public function same($pause = false)
	{
		$return = $this->last == $this->it[$this->field];
		if ($pause && !$return) $this->pause = true;
		return $return;
	}
/*
	public function valid()
	{
		if (!parent::valid()) return false;
		$c = $this->current();
		var_dump($c[$this->field]== $this->last);
		if ($c[$this->field] == $this->last) return true;
		if ($this->parent)
			return $this->parent->valid();

	}
*/
	public function sub($field)
	{
		return new Qi_It_SubGroup($this->it, $field, $this);
	}

	private function update_last()
	{
		if ($this->valid()) $this->last = $this->it[$this->field];
	}
}

class Qi_It_SubGroup extends NoRewindIterator
{
	private $field;
	private $last = null;
	private $it;
	private $parent;

	public function __construct($it, $field, $parent = null)
	{
		parent::__construct($it);
		$this->field = $field;
		$this->it = $it;
		$this->parent = $parent;
		$this->update_last();
	}

	public function next()
	{
		do {
			parent::next();
		}while(parent::valid() && $this->same());
		$this->update_last();
	}

	public function valid()
	{
		return parent::valid() && $this->same();
	}

	public function same()
	{
		return $this->parent->same(true) && $this->last == $this->it[$this->field];
	}

	private function update_last()
	{
		if (parent::valid() && isset($this->it[$this->field])) $this->last = $this->it[$this->field];
	}
}

//__HALT_COMPILER();
?>

<ol>
<?
$categorias = new Qi_It_Group($result, "categoria");
foreach($categorias as $categoria): ?>
	<li><h3><?= $categoria["categoria"] ?> - <?= $categoria["id"] ?></h3>
		<ul>
			<?
			$sub_categorias = $categorias->sub("sub");
			foreach($sub_categorias as $sub): ?>
			<li><h4><?= $sub["sub"] ?></h4>
			</li>
			<? endforeach ?>
		</ul>
	</li>
<? endforeach; ?>
</ol>

<pre>
<?= h($result->toXml()) ?>
</pre>